package nl.rainbowsheep.reisorg.rest.service.service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import nl.rainbowsheep.reisorg.rest.service.model.BurritoUser;
import nl.rainbowsheep.reisorg.rest.service.model.BurritoRole;
import nl.rainbowsheep.reisorg.rest.service.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

/**
 * Service class for users.
 */
@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private RoleService rolService;

    public Page<BurritoUser> findAll(Pageable pageable) {
        return userRepository.findAll(pageable);
    }

    public BurritoUser findByBurritoUserId(long burritoUserId) {
        return userRepository.findOne(burritoUserId);
    }

    public BurritoUser findByUsername(String username) {
        return userRepository.findByUsername(username);
    }

    public BurritoUser save(BurritoUser user) {
        //when registering a new user the user is activated (enabled = true)
        //An update of a burritoUser e.g. by a password reset, the user does not 
        //need to be set enabled anymore and the registration date need to be untouched
        if (findByUsername(user.getUsername()) == null) {
            user.setEnabled(true);
            user.setRegistrationDate(new Timestamp(new Date().getTime()));
        }
        BurritoUser userSaved = userRepository.save(user);

        if (user.getId() == -1) {
            setRolForUser(userSaved, "klant");
            return userRepository.save(userSaved);
        }
        return userSaved;
    }

    private void setRolForUser(BurritoUser burritoUser, String rolname) {
        List<BurritoRole> rollen = burritoUser.getBurritoUserRoles();
        if (rollen == null) {
            rollen = new ArrayList<BurritoRole>();
        }
        BurritoRole klantRol = rolService.findByName(rolname);
        rollen.add(klantRol);
        burritoUser.setBurritoUserRoles(rollen);
    }
}
